﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default3 : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (!Page.IsPostBack)
		{
			GridView1.DataSource = DbClass.GetDataTable(DbClass.GetSqlConnection(), "SELECT 姓名,性别,水果 FROM 选水果 ORDER BY 姓名,性别");
			GridView1.DataBind();
		}

	}
	protected void Button1_Click(object sender, EventArgs e)
	{
		DataTable oldDataTable = DbClass.GetDataTable(DbClass.GetSqlConnection(), "SELECT 姓名,性别,水果 FROM 选水果 ORDER BY 姓名,性别");
		DataTable newDataTable = new DataTable();

		DataColumn dataColumn = new DataColumn("姓名", typeof(string));
		newDataTable.Columns.Add(dataColumn);

		dataColumn = new DataColumn("性别", typeof(string));
		newDataTable.Columns.Add(dataColumn);

		dataColumn = new DataColumn("水果1", typeof(string));
		newDataTable.Columns.Add(dataColumn);

		dataColumn = new DataColumn("水果2", typeof(string));
		newDataTable.Columns.Add(dataColumn);

		dataColumn = new DataColumn("水果3", typeof(string));
		newDataTable.Columns.Add(dataColumn);

		string currentName = "";
		string previousName = "###";

		int fruitCount = 0;
		int newDataRowIndex = -1;

		foreach (DataRow currentRow in oldDataTable.Rows)
		{
			currentName = currentRow["姓名"].ToString();
			if (currentName == previousName)
			{
				if (fruitCount == 1)
				{
					newDataTable.Rows[newDataRowIndex]["水果2"] = currentRow["水果"];
					fruitCount = 2;
				}
				else if (fruitCount == 2)
				{
					newDataTable.Rows[newDataRowIndex]["水果3"] = currentRow["水果"];
					fruitCount = 3;
				}
				else if(fruitCount == 3)
				{
					fruitCount = 0;
				}
			}
			else
			{
				
				DataRow dataRow = newDataTable.NewRow();
				dataRow["姓名"] = currentName;
				dataRow["性别"] = currentRow["性别"];
				dataRow["水果1"] = currentRow["水果"];
				newDataTable.Rows.Add(dataRow);
				fruitCount = 1;
				newDataRowIndex++;
				previousName = currentName;
			}
		}

		GridView2.DataSource = newDataTable;
		GridView2.DataBind();
	}
}
